package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.BasicJoinFile;
import org.kl.bf.repository.basic.BasicJoinFileDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:11:30
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class BasicJoinFileService {

	private BasicJoinFileDao basicJoinFileDao;

	public BasicJoinFile getBasicJoinFile(String id) {
		return basicJoinFileDao.findOne(id);
	}

	public void saveBasicJoinFile(BasicJoinFile entity) {
		basicJoinFileDao.save(entity);
	}

	public void deleteBasicJoinFile(String id) {
		basicJoinFileDao.delete(id);
	}

	/**
	 * 删除多条记录
	 * 
	 * @param ids
	 */
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				basicJoinFileDao.delete(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}

	public List<BasicJoinFile> getAllBasicJoinFile() {
		return basicJoinFileDao.findAll();
	}

	public Page<BasicJoinFile> getUserBasicJoinFile(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<BasicJoinFile> spec = buildSpecification(searchParams);

		return basicJoinFileDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BasicJoinFile> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<BasicJoinFile> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), BasicJoinFile.class);
		return spec;
	}

	@Autowired
	public void setBasicJoinFileDao(BasicJoinFileDao basicJoinFileDao) {
		this.basicJoinFileDao = basicJoinFileDao;
	}

}
